/*
 * @Author: moonwater 13812995013@163.com
 * @Date: 2025-03-17 10:13:42
 * @LastEditors: moonwater 13812995013@163.com
 * @LastEditTime: 2025-03-17 11:28:11
 * @FilePath: \盐师22Git仓库\day16\TcpServer.java
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package day16;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) throws Exception {
        //创建服务器对象 指定程序端口
        //指定ip？ ip(计算机联网后自动分配)
        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器:" + server);
        //等待客户端连接 - 程序阻塞
        Socket client = server.accept();
        System.out.println("客户端连接成功" +client);
        //创建IO流对象
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();
        //服务器端接收客户端发送的内容
        byte[] b = new byte[1024];
        int length = is.read(b);
        if (length != -1) {
            //输出读到的内容数组 b
            System.out.println(new String(b,0,length));
        }
        //服务器收到客户端的数据之后给客户端发送消息
        String string = "Hello,Client,我是server";
        byte[] b1 = string.getBytes();
        os.write(b1);
        //关闭资源
        is.close();
        os.close();
        client.close();
        server.close();

    }
}
